//
//  JDAddressPickerView.swift
//  DragonWallet
//
//  Created by volantPig on 2024/7/29.
//

import UIKit
protocol JDAddressPickerViewDelegate: NSObjectProtocol {
    func selectAddressFinish()
}

class JDAddressPickerView: UIViewController {
    
    lazy var inserts: UIEdgeInsets = {
        if #available(iOS 11.0, *) {
            let insets = UIApplication.shared.delegate?.window??.safeAreaInsets ?? UIEdgeInsets.zero
            return insets
        } else {
            return UIEdgeInsets.zero
        }
    }()
   
    var pickerBackView: UIView?
    var pickerView: UIPickerView?
    var provinceModelArray: [ProvinceModel]?
    var cancelButton: UIButton?
    var confirmButton: UIButton?
    
    var cityArray: [CityModel]?
    var areaArray: [AreaModel]?
    
    var rowOfProvince: Int = 0
    var rowOfCity: Int = 0
    var rowOfArea: Int = 0
    
    weak var myDelegate: JDAddressPickerViewDelegate?

    var provinceName: String?
    var provinceCode: String?
    var cityName: String?
    var cityCode: String?
    var areaName: String?
    var areaCode: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addBlackView()
        self.getDataSource()
        self.createUI()
        
        // Do any additional setup after loading the view.
    }
    
    func createUI() {
        self.pickerBackView = UIView()
        self.view.addSubview(self.pickerBackView!)
        self.pickerBackView?.frame = CGRect.init(x: 0, y: screenHeight - self.inserts.bottom, width: screenWidth, height: 237 * fitHeight)
        self.view.addSubview(self.pickerBackView!)
        self.pickerBackView?.backgroundColor = UIColor.init(red: 237.0/255.0, green: 236.0/255.0, blue: 244.0/255.0, alpha: 1)
        
        self.pickerView = UIPickerView.init(frame: CGRect.init(x: 0, y: 37 * fitHeight, width: screenWidth, height: 200 * fitHeight))
        self.pickerView?.backgroundColor = UIColor.white
        self.pickerView?.delegate = self
        self.pickerView?.dataSource = self
        self.pickerBackView?.addSubview(self.pickerView!)
        
        self.cancelButton = UIButton.init(type: .system)
        self.pickerBackView?.addSubview(self.cancelButton!)
        self.cancelButton?.snp.makeConstraints({ (make) in
            make.left.equalTo(self.pickerBackView!).offset(20 * fitWidth)
            make.top.equalTo(self.pickerBackView!)
            make.height.equalTo(37 * fitHeight)
        })
        self.cancelButton?.buttonConfig(normalTitle: "取消", normalImageNamed: "", normalTitleColor: color("#262626"), titleFont: systemFont(16), backgroundColor: .white)
        self.cancelButton?.addTarget(self, action: #selector(closePickerView), for: UIControl.Event.touchUpInside)
        
        self.confirmButton = UIButton.init(type: .system)
        self.pickerBackView?.addSubview(self.confirmButton!)
        self.confirmButton?.snp.makeConstraints({ (make) in
            make.right.equalTo(self.pickerBackView!).offset(-20 * fitWidth)
            make.top.equalTo(self.pickerBackView!)
            make.height.equalTo(37 * fitHeight)
        })
        self.confirmButton?.buttonConfig(normalTitle: "确定", normalImageNamed: "", normalTitleColor: color("#262626"), titleFont: systemFont(16), backgroundColor: .white)
        self.confirmButton?.addTarget(self, action: #selector(selectAddressFinish), for: UIControl.Event.touchUpInside)
    }
    
    func getDataSource() {
        let path = Bundle.main.path(forResource: "ChineseCity", ofType: "plist")
        let tempProvinceArr = NSArray.init(contentsOfFile: path!)!
        
        self.provinceModelArray = [ProvinceModel]()
        
        for model in tempProvinceArr {
            let pro = ProvinceModel.init(JSON: model as! [String : Any])
            self.provinceModelArray?.append(pro!)
        }
    }
    
    func addBlackView() {
        let blackView = UIView()
        self.view.addSubview(blackView)
        blackView.frame = CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
        blackView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        let closeTap = UITapGestureRecognizer.init(target: self, action: #selector(closePickerView))
        blackView.addGestureRecognizer(closeTap)
    }
    
    /// 关闭pickerView
    @objc func closePickerView() {
        print("关闭pickerView")
        self.hidePickerView()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
             self.view.removeFromSuperview()
        }
       
    }
    
    @objc func selectAddressFinish() {
        let provinceModel = self.provinceModelArray![self.rowOfProvince]
        let cityModel = provinceModel.cityArray![self.rowOfCity]
        let areaModel = cityModel.areaArray![self.rowOfArea]

        self.provinceName = provinceModel.provinceName
        self.provinceCode = provinceModel.provinceCode
        self.cityName = cityModel.cityName
        self.cityCode = cityModel.cityCode
        self.areaName = areaModel.areaName
        self.areaCode = areaModel.areaCode
        self.closePickerView()
        self.myDelegate?.selectAddressFinish()
        
//        print("当前选择的是:\(provinceModel.provinceName)->\(cityModel.cityName)->\(areaModel.areaName)")
//        print("当前选择的是:\(provinceModel.provinceCode)->\(cityModel.cityCode)->\(areaModel.areaCode)")
    }
    
    func showPickerView() {
        UIView.animate(withDuration: 0.3) {
            self.pickerBackView?.frame = CGRect.init(x: 0, y: screenHeight - 237 * fitHeight, width: screenWidth, height: 237 * fitHeight)
        }
    }

    func hidePickerView() {
        UIView.animate(withDuration: 0.3) {
            self.pickerBackView?.frame = CGRect.init(x: 0, y: screenHeight - self.inserts.bottom, width: screenWidth, height: 237 * fitHeight)
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDAddressPickerView: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return self.provinceModelArray?.count ?? 0
        } else if component == 1 {
            let provinceModel = self.provinceModelArray![self.rowOfProvince]
            return provinceModel.cityArray?.count ?? 0
        } else if component == 2 {
            let provinceModel = self.provinceModelArray![self.rowOfProvince]
            let cityMode = provinceModel.cityArray![self.rowOfCity]
            return cityMode.areaArray?.count ?? 0
        }
        return 0
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        
        if component == 0 {
            let provinceModel = self.provinceModelArray![row]
            return provinceModel.provinceName
        } else if component == 1 {
            let provinceModel = self.provinceModelArray![self.rowOfProvince]
            let cityModel = provinceModel.cityArray![row]
            return cityModel.cityName
        } else if component == 2 {
            let provinceModel = self.provinceModelArray![self.rowOfProvince]
            let cityModel = provinceModel.cityArray![self.rowOfCity]
            let areaModel = cityModel.areaArray![row]
            return areaModel.areaName
        }
        return ""
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print("停下来了")
        if component == 0 {
            self.rowOfProvince = row
            self.rowOfCity = 0
            self.rowOfArea = 0
            self.pickerView?.reloadComponent(1)
            self.pickerView?.reloadComponent(2)
            self.pickerView?.selectRow(0, inComponent: 1, animated: true)
            self.pickerView?.selectRow(0, inComponent: 2, animated: true)
            
        } else if component == 1 {
            self.rowOfCity = row
            self.rowOfArea = 0
            self.pickerView?.reloadComponent(2)
            self.pickerView?.selectRow(0, inComponent: 2, animated: true)
        } else if component == 2 {
            self.rowOfArea = row
        }
        //        self.pickerView?.reloadAllComponents()
    }
    
}
